const initialState = {
  list: [
    { id: 1, task: '吃饭', isDone: true },
    { id: 2, task: '睡觉', isDone: false },
  ],
  type: 'all',
};
//定义action类型
export type typeAction =
  | {
      type: 'todo/updateById';
      payload: number;
    }
  | {
      type: 'todo/deleteById';
      payload: number;
    }
  | {
      type: 'todo/clearDone';
    }
  | {
      type: 'todo/addMsg';
      payload: {
        id: number;
        task: string;
        isDone: boolean;
      };
    }
  | {
      type: 'todo/changeStatus';
      payload: string;
    }
  | {
      type: 'todo/checkedAll';
      payload: boolean;
    };

// 注意这里的action不需要解构
export default function todoReducer(state = initialState, action: typeAction): typeof initialState {
  switch (action.type) {
    case 'todo/updateById':
      return {
        ...state,
        list: state.list.map((item) => {
          return { ...item, isDone: item.id === action.payload ? !item.isDone : item.isDone };
        }),
      };
    case 'todo/deleteById':
      return {
        ...state,
        list: state.list.filter((item) => item.id !== action.payload),
      };
    case 'todo/clearDone':
      return {
        ...state,
        list: state.list.filter((item) => !item.isDone),
      };
    case 'todo/addMsg':
      return {
        ...state,
        list: [action.payload, ...state.list],
      };
    case 'todo/changeStatus':
      return {
        ...state,
        type: action.payload,
      };
    case 'todo/checkedAll':
      return {
        ...state,
        list: state.list.map((item) => {
          return { ...item, isDone: action.payload };
        }),
      };
    default:
      return state;
  }
}
